﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

#include <QNetworkInterface>
#include <QBuffer>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_webSvr = new QWebSocketServer(QStringLiteral("Echo Server"),QWebSocketServer::NonSecureMode, this);
    m_webSvr->listen(QHostAddress::Any,9000);
    connect(m_webSvr, &QWebSocketServer::newConnection,this, &MainWindow::onNewConnection);
    connect(m_webSvr, &QWebSocketServer::closed, this, &MainWindow::closed);
    connect(&m_timer,&QTimer::timeout,this,&MainWindow::slotTimerOut);
    m_timer.start(1000);
}

MainWindow::~MainWindow()
{
    m_webSvr->close();
    delete ui;
}

static bool subDevListSort(const webClientlist *info1, const webClientlist *info2)
{
    return info1->nCount > info2->nCount;  //降序排列
}

void MainWindow::devListSort(QList<webClientlist *> list)
{
    qSort(list.begin(), list.end(), subDevListSort);
    int nSendCount = 0;
    QJsonArray array;
    for(int i = 0; i <list.length(); i++)
    {
        webClientlist *p = list.at(i);
        if(u8"phone" == p->param)
        {
            nSendCount++;
            if(nSendCount > 4)
            {
                break;
            }
            QJsonObject obj;
            obj.insert("name", p->name);
            obj.insert("count",p->nCount);
            array.append(obj);
        }
    }
    //定时发送消息出去
    if(nSendCount >= 1)
    {
        QJsonDocument jsonDoc;
        jsonDoc.setArray(array);
        QByteArray byteArray = jsonDoc.toJson(QJsonDocument::Compact);
        QString strSendData = QString(byteArray);
        for(int i=0; i<m_list.size(); i++)
        {
            webClientlist *p = m_list.at(i);
            if(u8"screenweb" == p->param)
            {
                p->webclient->sendTextMessage(strSendData);
            }
        }
    }
}

void MainWindow::onNewConnection()
{
    QWebSocket *webClient = m_webSvr->nextPendingConnection();
    QString requesturl = webClient->requestUrl().toString();
    m_szLog = QString(u8"新客户端连接 LocalAddress=%1").arg(webClient->localAddress().toString());
    ui->listWidget->addItem(m_szLog);
    QString param = requesturl.right(requesturl.length() - requesturl.lastIndexOf('/') - 1);
    webClientlist *pClient = new webClientlist();
    pClient->webclient = webClient;
    pClient->param = param;
    pClient->name = "";
    pClient->nCount = 0;
    m_list.push_back(pClient);
    connect(webClient, &QWebSocket::textMessageReceived, this, &MainWindow::processTextMessage);
    connect(webClient, &QWebSocket::disconnected, this, &MainWindow::socketDisconnected);
}

void MainWindow::closed()
{
    qDebug() << "closed";
}

void MainWindow::slotTimerOut()
{
    if(m_list.isEmpty())
        return;
    devListSort(m_list);
}

void MainWindow::processTextMessage(QString message)
{
    QWebSocket *reply = (QWebSocket*)sender();
    QString requestUrl = reply->requestUrl().toString();
    QString param = requestUrl.right(requestUrl.length() - requestUrl.lastIndexOf('/') - 1);
    if(u8"screenweb" == param){
        qDebug() << u8"大屏web msg=" << message.toUtf8().data() << "url=" << requestUrl;
    }else if(u8"phone" == param){
        m_szLog = QString(u8"手机web msg=%1,url=%2").arg(message).arg(requestUrl);
        qDebug() << m_szLog.toUtf8().data();
        ui->listWidget->addItem(m_szLog);
        //1. 存储链表，找到对应的websocket，找到则++，统一个地址仅支持同时一个人参与.
        for(int i=0; i<m_list.count(); i++){
            webClientlist *tmp = m_list.at(i);
            if(tmp->webclient == reply){
                tmp->name = message.left(message.indexOf(':'));
                tmp->nCount = message.right(message.length() - message.indexOf(':') - 1).toInt();
            }
        }
    }
}

void MainWindow::socketDisconnected()
{
    qDebug() << "socketDisconnected";
//    if(NULL != m_webClient)
//    {
//        m_webClient->deleteLater();
//        m_webClient = NULL;
//    }
}

void MainWindow::on_pushButton_clicked()
{
    QString szLog = QString(u8"[{ \"name\":\"hello world!\",\"data\": [%1,2,3,4,5]}]");
//    m_webClient->sendTextMessage(szLog.toUtf8());
}
